<template>
  <div id='cate'>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <tree-table :data="cateList" :columns="columns" :selection-type="false" :expand-type="false" show-index
        index-text="#" border class="treeTable">
        <!-- 是否有效  -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted === false " style="color: green;"></i>
          <i class="el-icon-error" v-else style="color: red;"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0 ">一级</el-tag>
          <el-tag type="success" size="mini" v-else-if="scope.row.cat_level === 1 ">二级</el-tag>
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditCateDialog(scope.row.cat_id)">编辑
          </el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCate(scope.row.cat_id)">删除
          </el-button>
        </template>
      </tree-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[5, 10, 20, 30]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加分类 -->
    <el-dialog title="添加分类" :visible="addCateDialogVisible" width="50%" @close="addCateDialogClosed">
      <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="90px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- options用来指定数据源，props用来指定配置对象 -->
          <el-cascader expand-trigger="hover" :options="parentCateList" clearable change-on-select
            :props="cascaderProps" @change="parentCateChange" v-model="selectedKeys">
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addCate">确 定</el-button>
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类 -->
    <el-dialog title="编辑分类" :visible="editCateDialogVisible" width="50%" @close="editCateDialogClosed">
      <el-form :model="editCateForm" label-width="90px">
        <el-form-item label="分类名称">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editCate">确 定</el-button>
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: 'cate',
    data() {
      return {
        //  商品分类数据列表
        cateList: [],
        //  查询条件
        queryInfo: {
          type: 3,
          pagenum: 1,
          pagesize: 5
        },
        //  总数据条数
        total: 0,
        //  为table指定列的定义
        columns: [{
            label: '分类名称',
            prop: 'cat_name',
          },
          {
            label: '是否有效',
            //将当前列定义为模板列
            type: 'template',
            //表示当前列使用的模板名称
            template: 'isok'
          },
          {
            label: '排序',
            type: 'template',
            template: 'order'
          },
          {
            label: '操作',
            type: 'template',
            template: 'opt'
          }
        ],
        //  控制添加分类对话框的显示与隐藏
        addCateDialogVisible: false,
        //  添加分类的表单数据对象
        addCateForm: {
          //  将要添加的分类的名称
          cat_name: '',
          // 父级分类的id
          cat_pid: 0,
          // 分类的等级，默认要添加的是1级分类
          cat_level: 0
        },
        //  添加分类表单的验证规则
        addCateFormRules: {
          cat_name: [{
            required: true,
            message: '请输入分类名称',
            trigger: blur
          }]
        },
        //  父级分类的列表
        parentCateList: [],
        //  指定级联选择器的配置对象
        cascaderProps: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        //  选中的父级分类的id数
        selectedKeys: [],
        editCateDialogVisible: false,
        editCateForm: {},
      }
    },
    created() {
      this.getCateList()
    },
    methods: {
      //  获取商品分类数据
      async getCateList() {
        await this.$http.get('categories', {
          params: this.queryInfo
        }).then(res => {
          if (res.data.meta.status == 200) {
            this.cateList = res.data.data.result
            this.total = res.data.data.total
          } else {
            return this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 20000
            })
          }
        })
      },
      // 监听pagesize改变
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getCateList()
      },
      // 监听pagenum改变
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage
        this.getCateList()
      },
      //显示添加分类的对话框
      showAddCateDialog() {
        this.getParentCateList()
        this.addCateDialogVisible = true
      },
      // 获取父级分类的数据列表
      async getParentCateList() {
        await this.$http.get('categories', {
          params: {
            type: 2
          }
        }).then(res => {
          if (res.data.meta.status == 200) {
            this.parentCateList = res.data.data
          } else {
            return this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 20000
            })
          }
        })
      },
      // 选择项发生变化触发函数
      parentCateChange() {
        // 如果selectedKeys的length>0，说明选中了父级分类，否则没有选中任何父级分类
        if (this.selectedKeys.length > 0) {
          // 父级分类的id为所选中的数组的最后一位
          this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
          // 当前分类的等级就是所选中的数组的长度
          this.addCateForm.cat_level = this.selectedKeys.length
        } else {
          this.addCateForm.cat_pid = 0
          this.addCateForm.cat_level = 0
        }
      },
      // 监听添加分类对话框的关闭事件
      addCateDialogClosed() {
        this.addCateDialogVisible = false
        this.$refs.addCateFormRef.resetFields()
        this.selectedKeys = []
        this.addCateForm.cat_level = 0
        this.addCateForm.cat_pid = 0
      },
      // 点击按钮添加新的分类
      addCate() {
        this.$refs.addCateFormRef.validate(async (valid) => {
          if (valid) {
            await this.$http.post("categories", this.addCateForm).then(res => {
              if (res.data.meta.status == 201) {
                this.$message({
                  message: res.data.meta.msg,
                  type: 'success',
                  duration: 600
                })
                this.getCateList()
                this.addCateDialogVisible = false
              } else {
                this.$message({
                  message: res.data.meta.msg,
                  type: 'error',
                  duration: 2000
                })
              }
            })
          } else {
            return
          }
        })
      },
      // 显示编辑分类对话框
      async showEditCateDialog(id) {
        await this.$http.get(`categories/${id}`).then(res => {
          if (res.data.meta.status == 200) {
            this.editCateForm = res.data.data
            this.editCateDialogVisible = true
          } else {
            this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 2000
            })
          }
        })
      },
      // 关闭编辑对话框
      editCateDialogClosed() {
        this.editCateDialogVisible = false
      },
      // 编辑分类
      async editCate() {
        await this.$http.put("categories/" + this.editCateForm.cat_id, {
          cat_name: this.editCateForm.cat_name
        }).then(res => {
          if (res.data.meta.status == 200) {
            this.$message({
              message: res.data.meta.msg,
              type: 'success',
              duration: 600
            })
            this.getCateList()
            this.editCateDialogVisible = false
          } else {
            this.$message({
              message: res.data.meta.msg,
              type: 'error',
              duration: 2000
            })
          }
        })
      },
      // 删除分类
      async deleteCate(id) {
        await this.$confirm('确定删除该分类吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete("categories/" + id).then(res => {
            if (res.data.meta.status == 200) {
              this.getCateList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            } else {
              this.$message({
                type: 'error',
                message: res.data.meta.msg
              });
            }
          })
        }).catch(err => {
          return err
        });
      },
    },
  }
</script>
<style scoped>
  .treeTable {
    margin-top: 15px;
  }

  .el-cascader {
    width: 100%;
  }
</style>
